package elastic.learn.transport;

import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import utils.LogUtil;

import java.net.InetAddress;

public class ElasticsearchConfig {
    private static TransportClient client;

    public static TransportClient getElasticsearchClient() {
        try {
            Settings settings = Settings.builder()
                    .put("cluster.name", "my-esLearn")  //连接的集群名
                    .put("client.transport.ignore_cluster_name", true)  //如果集群名不对，也能连接
                    .build();
            //创建client
            client = new PreBuiltTransportClient(settings)
                    .addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));  //主机和端口号
            return client;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void print(DocWriteResponse response) {
        // Index name
        String _index = response.getIndex();
        // Type name
        String _type = response.getType();
        // Document ID (generated or not)
        String _id = response.getId();
        // Version (if it's the first time you index this document, you will get: 1)
        long _version = response.getVersion();
        // status has stored current instance statement.
        RestStatus status = response.status();
        LogUtil.i(_index + "  " + _type + "  " + _id + "  " + _version + "  " + status.toString());
    }

    public static void main(String[] args) {
        ElasticsearchConfig.getElasticsearchClient();
    }
}